package com.wtwd.campus.sms;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.wtwd.campus.common.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author ldaoliang
 * @Date create in 14:04 2021/3/18
 * @Description 发送国内短信
 */
public class SendToChina {

    private static final Logger logger = LoggerFactory.getLogger(SendToChina.class);

    /**
     * 云短信初始化
     *
     * @return
     * @throws ClientException
     */
    private static IAcsClient init() throws ClientException {
        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        // 初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile
                .getProfile(Constants.ALI_REGION_ID, Constants.accessKeyId, Constants.accessKeySecret);
        DefaultProfile.addEndpoint(Constants.ALI_REGION_ID, Constants.ALI_REGION_ID, Constants.ALI_PRODUCT, Constants.ALI_DOMAIN);
        return new DefaultAcsClient(profile);
    }

    /**
     * 发送验证码
     *
     * @param toPhone  接收验证码的手机号
     * @param code     验证码
     * @param codeType 验证码类型
     * @return
     */
    public static SendSmsResponse sendVerifyCode(String toPhone, String code, int codeType) {
        IAcsClient acsClient;
        SendSmsResponse sendSmsResponse = null;
        try {
            acsClient = init();
            // 组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            // 必填:待发送手机号。支持以逗号分隔的形式进行批量调用，"123,321"
            // 批量上限为1000个手机号码,发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000”
            request.setPhoneNumbers(toPhone);
            // 必填:短信签名-可在短信控制台中找到
            request.setSignName(Constants.signName);
            // 必填：短信模板，可在短信控制台中找到
            if (codeType == 1) {
                request.setTemplateCode(Constants.SMS_TEMPLATE_REGISTER);
            } else if (codeType == 2) {
                request.setTemplateCode(Constants.SMS_TEMPLATE_LOGIN);
            } else if (codeType == 3) {
                request.setTemplateCode(Constants.SMS_TEMPLATE_FORGET_PWD);
            }else {
                request.setTemplateCode(Constants.SMS_TEMPLATE_UPDATE_PHONE);
            }
            // 可选:模板中的变量替换JSON串
            request.setTemplateParam("{\"code\":\"" + code + "\"}");
            // hint 此处可能会抛出异常，注意catch
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return sendSmsResponse;
    }

    public static void main(String[] args) {
        sendVerifyCode("13669061320","124596",3);
    }
}
